package com.example.review.ParseData;

import android.util.Log;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * SAX解析XML
 */

/**
 * 需要解析的数据
 */
//    <apps>
//        <app>
//            <id>1</id>
//            <name>Google Maps</name>
//            <version>1.0</version>
//        </app>
//        <app>
//            <id>2</id>
//            <name>Chrome</name>
//            <version>2.1</version>
//        </app>
//        <app>
//            <id>3</id>
//            <name>Google Play</name>
//            <version>2.3</version>
//        </app>
//    </apps>
public class MyContentHandle extends DefaultHandler {

    private String nodeName;
    private StringBuilder id;
    private StringBuilder name;
    private StringBuilder version;
    @Override
    //开始XML解析的时候调用
    public void startDocument() throws SAXException {
        super.startDocument();
        id = new StringBuilder();
        name = new StringBuilder();
        version = new StringBuilder();
    }

    @Override
    //在开始解析某个节点的时候调用
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        // 记录当前节点名
        nodeName = localName;
    }

    @Override
    //在获 取节点中内容的时候调用
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        // 根据当前的节点名判断将内容添加到哪一个StringBuilder对象中
        if ("id".equals(nodeName)) {
            id.append(ch, start, length);
        }
        else if ("name".equals(nodeName)) {
            name.append(ch, start, length);
        }
        else if ("version".equals(nodeName)) {
            version.append(ch, start, length);
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if ("app".equals(localName)) {
            Log.d("ContentHandler", "id is " + id.toString().trim());
            Log.d("ContentHandler", "name is " + name.toString().trim());
            Log.d("ContentHandler", "version is " + version.toString().trim());
            //最后要将StringBuilder清空掉
            id.setLength(0);
            name.setLength(0);
            version.setLength(0);
        }
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

}
